<script setup>
import {
  ref,
  reactive,
  toRefs,
  shallowRef,
  nextTick,
  defineExpose,
  watch,
  onMounted,
  onUnmounted
} from "vue";

import { protocolList } from "../assets/protocolList.js";
import {
  modifyDeviceList,
  deviceConfig,
  deviceCompile,
  deviceSend
} from "@/api/DevConnection.js";
import { message } from "@/utils/message";
import { useDrawerStore } from "@/store/drawerDataStores.js";

import componentList from "./index.js";
import { sendWebSocket, WebSocketOnclose } from "@/api/WebSocket";

const drawerStore = useDrawerStore();

const childFuncRef = ref(),
  publicForm = ref({
    inputGatewayId: undefined,
    selectedInterface: undefined,
    selectedProtocol: undefined
  }),
  gatewayStatus = ref(""),
  protocolStatus = ref(""),
  compileRate = ref(0),
  issueRate = ref(0),
  compileDisabled = ref(true),
  issueDisabled = ref(true);
const ruleFormRef = ref(),
  ruleFormLeftRef = ref(),
  ruleFormLeft = ref({}),
  tableData = ref([]);
const props = defineProps({
  protocolConfigDrawer: {
    type: Boolean,
    default: false
  },
  devVarTableSelectedItem: {
    type: Object,
    default() {
      return {};
    }
  }
  // tableSelectedId: {
  //   type: Number,
  //   default: ''
  // }
});
const { protocolConfigDrawer, devVarTableSelectedItem } = toRefs(props);
const emit = defineEmits([
  "childProtocolDrawer",
  "childGetApiTableDataList",
  "childFormObj"
]);

watch(
  () => [
    publicForm.value.inputGatewayId,
    publicForm.value.selectedInterface,
    publicForm.value.selectedProtocol
  ],
  (newValue, oldValue) => {}
);

onMounted(() => {
  // Socket初始化
  sendWebSocket(socket, 100);
  if (devVarTableSelectedItem.value) {
    loadInitialData(); // 加载状态
  } else {
    console.log("Data not loaded yet");
  }
});

onUnmounted(() => {
  WebSocketOnclose();
});
// 确定按钮
const confirmClick1 = () => {
  if (
    publicForm.value.inputGatewayId &&
    publicForm.value.selectedInterface &&
    publicForm.value.selectedProtocol
  ) {
    // 检查数组中是否已经存在完全相同的对象
    let isDuplicate = tableData.value.some(obj => {
      return (
        obj.inputGatewayId === publicForm.value.inputGatewayId &&
        obj.selectedInterface === publicForm.value.selectedInterface &&
        obj.selectedProtocol === publicForm.value.selectedProtocol
      );
    });
    if (!isDuplicate) {
      tableData.value.push({
        inputGatewayId: publicForm.value.inputGatewayId,
        selectedInterface: publicForm.value.selectedInterface,
        selectedProtocol: publicForm.value.selectedProtocol
      });
    }
  }
};
// 删除按钮
const deleteClick = () => {
  if (selectedKey.value.length === 0) {
    message("请选择要删除的数据", { type: "warning" });
    return;
  }
  tableData.value = tableData.value.filter(
    row => !selectedKey.value.includes(row)
  );
  selectedKey.value = [];
};
// table多选事件
const selectedKey = ref([]);
const handleSelectionChange = keys => {
  selectedKey.value = keys;
};
// 协议更改事件
const protocolLabel = ref("");
const component = shallowRef(null);
// const protocolChange = value => {
//   let strName = "";
//   if (value) {
//     protocolList.forEach(item => {
//       if (item.value === value) {
//         protocolLabel.value = item.label;
//       }
//     });
//     strName = protocolLabel.value.replace(/\s+/g, "");
//   }
//   componentList.value.filter(item => {
//     if (item.key === strName) {
//       component.value = item.component;
//     }
//   });
//   if (component.value) {
//     nextTick(() => {
//       childFuncRef.value.clearVar();
//     });
//   }
// };
let isProcessing = false; // 防止并发处理
const socket = SocketData => {
  console.log("SocketData 结构:", SocketData); // 查看实际结构
  if (isProcessing) return; // 如果还在处理，则不继续处理新的消息
  isProcessing = true;
  let compile_timer = 0;

  // 解析收到的 JSON 数据
  const parsedData = JSON.parse(SocketData); // 解析后的数据
  console.log("解析后数据", parsedData);
  console.log("按钮状态", compileDisabled.value);
  // 显示协议适配状态
  protocolStatus.value = parsedData.data;

  if (parsedData.data === "配置完成") {
    Vue.nextTick(() => {
      compileDisabled.value = false;
    });
  }

  if (parsedData.data === "编译中") {
    console.log("Starting compile progress update..."); // 检查是否进入到这里
    compile_timer = setInterval(() => {
      console.log("Current compileRate:", compileRate.value); // 检查编译进度是否正常递增
      if (compileRate.value < 90) {
        compileRate.value++;
      } else {
        console.log("Stopping compile progress update...");
        clearInterval(compile_timer);
      }
    }, 60);
  } else if (parsedData.data === "编译完成") {
    compileRate.value = 100;
    issueDisabled.value = false;
    clearInterval(compile_timer);
  } else if (parsedData.data === "下发中") {
    if (parsedData.hasOwnProperty("chunk_number") && issueRate.value < 100) {
      let resFloatVal =
        (parsedData.chunk_number / parsedData.total_chunks) * 100;
      let resVal = resFloatVal.toFixed(2);
      console.log(resVal);
      issueRate.value = parseFloat(resVal);
    }
  } else if (parsedData.data === "下发完成") {
    issueRate.value = 100;
    gatewayStatus.value = "运行";
  }
};

// 页面加载时，确保设置正确的初始值

// 配置按钮
const configClick = () => {
  compileRate.value = 0; // 初始进度条值为 0
  issueRate.value = 0;
  protocolStatus.value = "未适配";
  gatewayStatus.value = "未运行";
  compileDisabled.value = true;
  issueDisabled.value = true;
  let MQTTObj = {}; // 初始化 MQTTObj

  if (selectedKey.value.length > 0) {
    let readInfo = [];
    for (let i = 0; i < tableData.value.length; i++) {
      readInfo.push({
        inputGatewayId: tableData.value[i].inputGatewayId,
        selectedInterface: tableData.value[i].selectedInterface,
        selectedProtocol: tableData.value[i].selectedProtocol
      });
    }
    MQTTObj = {
      groups_num: tableData.value.length,
      read_info: readInfo
    };
    let SQLObj = { ...selectedKey.value[0], ...ruleFormLeft.value };
    let FormObj = {
      MQTTObj: MQTTObj,
      SQLObj: SQLObj
    };
    console.log("FormObj: ", FormObj);

    let jsonString = {
      edge_getway_ID: publicForm.value.inputGatewayId,
      device_name: devVarTableSelectedItem.value.deviceName,
      type: "type_demand",
      demand: {
        port: {
          port_name: publicForm.value.selectedInterface,
          port_info: publicForm.value.selectedInterface
        },
        protocol: {
          protocol_name: protocolLabel.value,
          protocol_info: MQTTObj
        }
      }
    };
    let submitObject = {
      data: JSON.stringify(jsonString),
      id: devVarTableSelectedItem.value.id
    };
    deviceConfig(submitObject).then(res => {
      compileRate.value = 0;
      issueRate.value = 0;
      protocolStatus.value = "配置中";
      gatewayStatus.value = "预运行";
      console.log(res); // 打印 res 看看返回了什么
      if (res.status === 200) {
        // saveDeviceItem(SQLObj);
        const messageElement = document.createElement("div");
        messageElement.textContent = "配置完成";
        messageElement.style.position = "fixed";
        messageElement.style.top = "-50px"; // 初始位置在视口上方
        messageElement.style.left = "50%";
        messageElement.style.transform = "translateX(-50%)";
        messageElement.style.backgroundColor = "#e6f7e6"; // 淡绿色背景
        messageElement.style.color = "#333";
        messageElement.style.padding = "15px 30px";
        messageElement.style.fontSize = "16px";
        messageElement.style.fontWeight = "normal";
        messageElement.style.zIndex = "99999";
        messageElement.style.borderRadius = "8px";
        messageElement.style.boxShadow = "0 2px 4px rgba(0, 0, 0, 0.1)";
        messageElement.style.opacity = "0"; // 初始透明度为 0
        messageElement.style.transition = "top 0.5s ease, opacity 0.5s ease"; // 过渡效果
        messageElement.style.display = "flex";
        messageElement.style.alignItems = "center";

        // 添加小勾图标的样式
        const checkIcon = document.createElement("span");
        checkIcon.innerHTML = "&#10004;"; // Unicode 绿色小勾
        checkIcon.style.color = "#52c41a"; // 设置勾的颜色为绿色
        checkIcon.style.fontSize = "20px";
        checkIcon.style.marginRight = "10px"; // 给小勾和文本之间一些间距

        // 将小勾图标插入到 messageElement 里
        messageElement.insertBefore(checkIcon, messageElement.firstChild);

        document.body.appendChild(messageElement);

        // 使用 setTimeout 触发过渡效果
        setTimeout(() => {
          messageElement.style.top = "20px"; // 滑动到目标位置
          messageElement.style.opacity = "1"; // 显示弹窗
        }, 0);

        // 在 5 秒后自动隐藏
        setTimeout(() => {
          messageElement.style.opacity = "0"; // 隐藏
          messageElement.style.top = "-50px"; // 滑动回去
          setTimeout(() => {
            document.body.removeChild(messageElement); // 隐藏后移除节点
          }, 500); // 等待过渡效果结束再移除
        }, 3000);
        protocolStatus.value = "配置完成";
        compileRate.value = 0; // 初始进度条值为 0
        issueRate.value = 0;
        compileDisabled.value = false;
        issueDisabled.value = true;
      } else {
        protocolStatus.value = "配置失败";
        message(res.message, { type: "error" });
      }
    });
  } else {
    message("请选择你要配置的协议", { type: "warning" });
  }
};
//   deviceConfig(submitObject).then(res => {
//     compileRate.value = 0;
//     issueRate.value = 0;
//     protocolStatus.value = "配置中";
//     gatewayStatus.value = "预运行";
//     if (res.status === 200) {
//       saveDeviceItem(childObject.SQLObj);

//       // const resultData = JSON.parse(res.data);
//       // compileDisabled.value = true;
//       // protocolStatus.value = resultData.msg;
//       // // gatewayStatus.value = '预运行';
//       // compileDisabled.value = false;
//       // console.log(JSON.parse(res.data));
//     } else {
//       protocolStatus.value = "配置失败";
//       message(res.message, { type: "error" });
//     }
//   });
// websocket后端返回数据

// 编译按钮
// const compileClick = () => {
//   let jsonString = {
//     edge_getway_ID: publicForm.value.inputGatewayId, //网关ID
//     device_name: devVarTableSelectedItem.value.deviceName, //设备名称/编号
//     type: "type_cmd", //类型为需求类型
//     cmd: "build_cmd" //编译指令
//   };
//   let submitObject = {
//     data: JSON.stringify(jsonString)
//   };
//   protocolStatus.value = "编译中";

//   // let compile_timer = setInterval(()=>{
//   //   protocolStatus.value = "编译中";
//   //   if(compileRate.value < 90){
//   //     compileRate.value++;
//   //   } else {
//   //     clearInterval(compile_timer);
//   //   }
//   // },60)
//   deviceCompile(submitObject)
//     .then(res => {
//       if (res.status === 200) {
//         // compileRate.value = 100;
//         // protocolStatus.value = "编译完成";
//         // issueDisabled.value = false;
//         // socket();
//       } else {
//         // clearInterval(compile_timer);
//         protocolStatus.value = "编译失败";
//         issueDisabled.value = true;
//       }
//     })
//     .catch(err => {
//       console.log(err);
//     });
// };
const loadInitialData = () => {
  // 检查当前状态并设置初始值
  if (devVarTableSelectedItem.value.state === 1) {
    issueDisabled.value = false;
    compileDisabled.value = false;
    compileRate.value = 100; // 如果已适配，设置为 100
    issueRate.value = 100;
    protocolStatus.value = "已适配";
    gatewayStatus.value = "运行";
  } else {
    issueDisabled.value = true;
    compileDisabled.value = true;
    compileRate.value = 0; // 初始进度条值为 0
    issueRate.value = 0;
    protocolStatus.value = "未适配";
    gatewayStatus.value = "未运行";
  }

  nextTick(() => {
    console.log("页面加载时更新进度条");
  });
};

// 编译按钮
const compileClick = () => {
  // 清零进度条和状态
  compileRate.value = 0;
  protocolStatus.value = "准备编译";

  let jsonString = {
    edge_getway_ID: publicForm.value.inputGatewayId, // 网关ID
    device_name: devVarTableSelectedItem.value.deviceName, // 设备名称/编号
    type: "type_cmd", // 类型为需求类型
    cmd: "build_cmd" // 编译指令
  };
  let submitObject = {
    data: JSON.stringify(jsonString)
  };

  protocolStatus.value = "编译中";
  gatewayStatus.value = "预运行";

  // 模拟编译进度条更新
  let compile_timer = setInterval(() => {
    // 每60ms进度增加，直到90%
    if (compileRate.value < 90) {
      compileRate.value++;
    } else {
      clearInterval(compile_timer); // 达到90%时停止
    }
  }, 90);

  // 发起编译请求
  deviceCompile(submitObject)
    .then(res => {
      if (res.status === 200) {
        // 请求成功，完成进度条并更新状态
        compileRate.value = 100;
        protocolStatus.value = "编译完成";
        issueDisabled.value = false; // 解锁“下发”按钮
      } else {
        // 请求失败时的处理
        protocolStatus.value = "编译失败";
        issueDisabled.value = true;
      }
    })
    .catch(err => {
      console.error(err);
      protocolStatus.value = "编译失败";
    })
    .finally(() => {
      clearInterval(compile_timer); // 确保计时器被清除
    });
};

// 下发按钮
// const issueTimer = ref(0);
// const issueClick = () => {
//   let jsonString = {
//     edge_getway_ID: publicForm.value.inputGatewayId, //网关ID
//     device_name: devVarTableSelectedItem.value.deviceName, //设备名称/编号
//     type: "type_cmd", //类型为需求类型
//     cmd: "send_cmd" //下发指令
//   };
//   let submitObject = {
//     data: JSON.stringify(jsonString)
//   };
//   protocolStatus.value = "下发中";

//   // let issue_timer = setInterval(()=>{
//   //   protocolStatus.value = "下发中";
//   //   if(issueRate.value < 90){
//   //     issueRate.value++;
//   //   } else {
//   //     clearInterval(issue_timer);
//   //   }
//   // },60)
//   deviceSend(submitObject)
//     .then(res => {
//       if (res.status === 200) {
//         // const resultData = JSON.parse(res.data);
//         // if (resultData.msg === '下发完成') {
//         //   protocolStatus.value = "下发完成";
//         //   issueRate.value = 100;
//         // } else {
//         //   if (issueRate.value < 100) {
//         //     let resVal = ((resultData.chunk_number / resultData.total_chunks) * 100) .toFixed(2);
//         //     issueRate.value = parseFloat(resVal) + issueRate.value;
//         //   }
//         //   issueClick();
//         // }
//         // issueRate.value = 100;
//         // protocolStatus.value = "适配完成";
//         // gatewayStatus.value = "运行";
//       } else {
//         // clearInterval(issue_timer);
//         protocolStatus.value = "下发失败";
//       }
//     })
//     .catch(err => {
//       console.log(err);
//     });
// };

// 下发按钮

const issueClick = () => {
  // 清零进度条和状态
  issueRate.value = 0;
  protocolStatus.value = "准备下发";
  gatewayStatus.value = "预运行";
  let jsonString = {
    edge_getway_ID: publicForm.value.inputGatewayId, // 网关ID
    device_name: devVarTableSelectedItem.value.deviceName, // 设备名称/编号
    type: "type_cmd", // 类型为需求类型
    cmd: "send_cmd" // 下发指令
  };
  let submitObject = {
    data: JSON.stringify(jsonString)
  };

  protocolStatus.value = "下发中";
  gatewayStatus.value = "预运行";
  // 启动进度条
  let issue_timer = setInterval(() => {
    if (issueRate.value < 90) {
      issueRate.value++;
    } else {
      clearInterval(issue_timer); // 达到90%时停止
    }
  }, 30);

  let SQLObj = { ...selectedKey.value[0], ...ruleFormLeft.value };

  deviceSend(submitObject)
    .then(res => {
      if (res.status === 200) {
        const resultData = JSON.parse(res.data); // 解析返回数据
        // 检查返回消息，更新状态
        // if (res.status === 200) {
        protocolStatus.value = "下发完成";
        protocolStatus.value = "适配完成";
        gatewayStatus.value = "运行";
        issueRate.value = 100; // 设置进度为100%
        saveDeviceItem(SQLObj);
        // } else {
        // // 处理下发中的进度更新
        // if (
        //   resultData.hasOwnProperty("chunk_number") &&
        //   resultData.hasOwnProperty("total_chunks")
        // ) {
        //   let resVal = (
        //     (resultData.chunk_number / resultData.total_chunks) *
        //     100
        //   ).toFixed(2);
        //   issueRate.value += parseFloat(resVal); // 增加进度
        // }
        // }
      } else {
        // 处理下发中的进度更新
        if (
          resultData.hasOwnProperty("chunk_number") &&
          resultData.hasOwnProperty("total_chunks")
        ) {
          let resVal = (
            (resultData.chunk_number / resultData.total_chunks) *
            100
          ).toFixed(2);
          issueRate.value += parseFloat(resVal); // 增加进度
        }
        protocolStatus.value = "下发失败";
      }
    })
    .catch(err => {
      console.error(err);
      protocolStatus.value = "下发失败";
    })
    .finally(() => {
      clearInterval(issue_timer); // 确保计时器被清除
    });
};

// 清空已经填写的变量
const deleteVar = () => {
  protocolLabel.value = "";
  tableData.value = []; // 清空表格数据
};
// 抽屉取消按钮
const cancelClick = () => {
  emit("childProtocolDrawer", false);
};

// 抽屉关闭回调
const handleClose = () => {
  emit("childProtocolDrawer", false);
  if (publicForm.value.selectedProtocol) {
    deleteVar();
  }
  ruleFormRef.value.resetFields();
};

// 抽屉确定按钮
const confirmClick = () => {
  emit("childProtocolDrawer", false);
  drawerStore.inputGatewayId = publicForm.value.inputGatewayId;
  drawerStore.selectedInterface = publicForm.value.selectedInterface;
  drawerStore.selectedProtocol = publicForm.value.selectedProtocol;
  drawerStore.tableSelectedId = devVarTableSelectedItem.value.id;
  drawerStore.formTitle = protocolLabel.value;
  if (component.value) {
    nextTick(() => {
      childFuncRef.value.saveStore();
    });
  }
};

// 抽屉打开回调
const handleOpen = () => {
  console.log("抽屉打开，正在调用 loadInitialData");
  loadInitialData(); // 调用初始化加载函数

  let strName = "";
  // 确认 devVarTableSelectedItem 的值是否加载完成
  console.log("devVarTableSelectedItem:", devVarTableSelectedItem.value);

  if (devVarTableSelectedItem.value.state === 1) {
    publicForm.value = {
      inputGatewayId: devVarTableSelectedItem.value.gatewayId,
      selectedInterface: devVarTableSelectedItem.value.connector,
      selectedProtocol: devVarTableSelectedItem.value.protocol
    };

    // 解析 connector 数据
    const connectorData = devVarTableSelectedItem.value.createUser;
    if (connectorData) {
      const rows = connectorData.split(";").map(row => {
        const [inputGatewayId, selectedInterface, selectedProtocol] =
          row.split(",");
        return {
          inputGatewayId,
          selectedInterface,
          selectedProtocol
        };
      });

      tableData.value = rows; // 更新 tableData
    } else {
      tableData.value = []; // 如果没有 connector 数据，清空表格
    }

    // 打印 tableData 的值
    console.log("tableData after parsing connector:", tableData.value);

    protocolList.forEach(item => {
      if (item.value === devVarTableSelectedItem.value.protocol) {
        protocolLabel.value = item.label;
      }
    });
  } else if (!devVarTableSelectedItem.value.selectedProtocol) {
    component.value = null;
    publicForm.value = {};

    // 打印 tableData 的值
    console.log("tableData after no selectedProtocol:", tableData.value);

    return;
  }

  strName = protocolLabel.value.replace(/\s+/g, "");
  componentList.value.filter(item => {
    if (item.key === strName) {
      component.value = item.component;
    }
  });

  // 打印最终的 tableData
  console.log("Final tableData:", tableData.value);
};

// 父组件调用保存函数
const saveStore = () => {
  drawerStore.ruleFormLeft = { ...ruleFormLeft.value };
  drawerStore.RTUForm = { ...ruleForm.value };
  drawerStore.tableData = tableData.value;
};
defineExpose({
  saveStore
});

// 保存显示已适配
const saveDeviceItem = childObject => {
  let readInfo = [];
  for (let i = 0; i < tableData.value.length; i++) {
    readInfo.push({
      inputGatewayId: tableData.value[i].inputGatewayId,
      selectedInterface: tableData.value[i].selectedInterface,
      selectedProtocol: tableData.value[i].selectedProtocol
    });
  }
  let tableDataString = readInfo
    .map(
      item =>
        `${item.inputGatewayId},${item.selectedInterface},${item.selectedProtocol}`
    )
    .join(";");

  let parentObj = {
    id: devVarTableSelectedItem.value.id,
    deviceType: devVarTableSelectedItem.value.deviceType, // 设备类型
    deviceName: devVarTableSelectedItem.value.deviceName, // 设备名称
    deviceDescription: devVarTableSelectedItem.value.deviceDescription, // 设备描述
    state: 1, // 0:未适配，1：已适配
    gatewayId: publicForm.value.inputGatewayId, // 网关Id
    createUser: tableDataString, // 表格数据
    updateUser: devVarTableSelectedItem.value.updateUser, // 修改人
    isDeleted: 0, // 0：未删除，1：已删除
    connector: publicForm.value.selectedInterface, // 接口
    protocol: publicForm.value.selectedProtocol, // 协议
    passiveAddress: devVarTableSelectedItem.value.passiveAddress, // 从站地址
    passiveIp: devVarTableSelectedItem.value.passiveIp, // 从站ip
    passivePort: devVarTableSelectedItem.value.passivePort, // 端口号
    protocolType: devVarTableSelectedItem.value.protocolType, // 协议类型
    protocolAddress: devVarTableSelectedItem.value.protocolAddress, // 协议地址
    protocolNumber: devVarTableSelectedItem.value.protocolNumber, // 协议数量
    targetAddress: devVarTableSelectedItem.value.targetAddress, // 目标地址
    targetPort: devVarTableSelectedItem.value.targetPort, // 目标端口
    deviceAccount: devVarTableSelectedItem.value.deviceAccount, // 设备账户
    devicePassword: devVarTableSelectedItem.value.devicePassword, // 设备密码
    clientId: devVarTableSelectedItem.value.clientId, // ClientID
    subscribeTopic: devVarTableSelectedItem.value.subscribeTopic, // 订阅主题
    releaseTopic: devVarTableSelectedItem.value.releaseTopic, // 发布主题
    qos: devVarTableSelectedItem.value.qos, // QOS
    clearSession: devVarTableSelectedItem.value.clearSession, // 清理会话状态
    url: devVarTableSelectedItem.value.url, // URL
    securityPolicy: devVarTableSelectedItem.value.securityPolicy, // 安全策略
    nodePath: devVarTableSelectedItem.value.nodePath, // 节点路径
    certificates: devVarTableSelectedItem.value.certificates, // 证书和密钥
    readingMethod: devVarTableSelectedItem.value.readingMethod, // 数据读取方法
    timeoutSetting: devVarTableSelectedItem.value.timeoutSetting, // 超时设置
    baudRate: devVarTableSelectedItem.value.baudRate, // 波特率
    dataBit: devVarTableSelectedItem.value.dataBit, // 数据位
    stopBit: devVarTableSelectedItem.value.stopBit, // 停止位
    verify: devVarTableSelectedItem.value.verify, // 校验
    frameFormat: devVarTableSelectedItem.value.frameFormat, // 帧格式
    frameType: devVarTableSelectedItem.value.frameType, // 帧类型
    frameId: devVarTableSelectedItem.value.frameId, // 帧ID
    wifiAccount: devVarTableSelectedItem.value.wifiAccount, // WIFI账号
    wifiPassword: devVarTableSelectedItem.value.wifiPassword, // WIFI密码
    isSelected: 1 // 是否选中
  };

  const submitObject = { ...parentObj, ...childObject };
  modifyDeviceList(submitObject).then(res => {
    if (res.status === 200) {
      // compileRate.value = 0;
      // issueRate.value = 0;
      // protocolStatus.value = '配置中';
      // gatewayStatus.value = '预运行';
      // compileDisabled.value = true;
      // setTimeout(() => {
      //   protocolStatus.value = '配置完成';
      //   gatewayStatus.value = '预运行';
      //   compileDisabled.value = false;
      // }, 2000);
      emit("childGetApiTableDataList");
    } else {
      message(res.message, { type: "error" });
    }
  });
};
</script>

<template>
  <el-drawer
    :model-value="protocolConfigDrawer"
    direction="rtl"
    @open="handleOpen"
    @close="handleClose"
  >
    <template #header>
      <!-- <h4>协议配置</h4> -->
    </template>
    <template #default>
      <div class="drawer-main">
        <div class="drawer-one">
          <el-divider content-position="left">协议配置</el-divider>

          <el-form
            ref="ruleFormRef"
            :inline="true"
            :model="publicForm"
            label-position="top"
          >
            <el-form-item
              label="网关ID"
              style="width: 140px"
              prop="inputGatewayId"
              :rules="{
                required: true,
                message: '请输入网关ID',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="publicForm.inputGatewayId"
                clearable
                placeholder="请输入网关ID"
              />
            </el-form-item>
            <el-form-item
              label="接口"
              style="width: 140px"
              prop="selectedInterface"
              :rules="{
                required: true,
                message: '请选择接口',
                trigger: 'change'
              }"
            >
              <el-select
                v-model="publicForm.selectedInterface"
                placeholder="请选择接口"
              >
                <el-option label="无接口" value="无接口" />
                <el-option label="RJ45_1" value="RJ45_1" />
                <el-option label="RJ45_2" value="RJ45_2" />
              </el-select>
            </el-form-item>
            <el-form-item
              label="协议"
              style="width: 140px"
              prop="selectedProtocol"
              :rules="{
                required: true,
                message: '请选择接口',
                trigger: 'change'
              }"
            >
              <el-select
                v-model="publicForm.selectedProtocol"
                placeholder="请选择协议"
                @change="protocolChange"
              >
                <el-option
                  v-for="item in protocolList"
                  :key="item"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="form-btn" @click="confirmClick1"
                >确定</el-button
              >
              <el-button type="primary" class="form-btn" @click="deleteClick"
                >删除</el-button
              >
            </el-form-item>
          </el-form>
        </div>

        <div class="form-main">
          <div class="form-table">
            <el-table
              ref="multipleTableRef"
              class="custom-table"
              :data="tableData"
              border
              stripe
              max-height="200"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" align="center" />
              <el-table-column
                prop="inputGatewayId"
                label="网关ID"
                align="center"
              />
              <el-table-column
                prop="selectedInterface"
                label="接口"
                align="center"
              />
              <el-table-column
                prop="selectedProtocol"
                label="协议"
                align="center"
              />
            </el-table>
          </div>
          <div class="config-btn">
            <el-button type="primary" @click="configClick">配置</el-button>
          </div>
        </div>
        <div class="drawer-three">
          <el-divider content-position="left">协议更新与部署</el-divider>
          <div class="three-main">
            <div class="three-item">
              <div class="progress-box">
                <el-progress
                  :percentage="compileRate"
                  :text-inside="true"
                  :stroke-width="30"
                />
              </div>
              <el-button
                link
                type="primary"
                :disabled="compileDisabled"
                @click="compileClick"
                >编译</el-button
              >
            </div>
            <div class="three-item">
              <div class="progress-box">
                <el-progress
                  :percentage="issueRate"
                  :text-inside="true"
                  :stroke-width="30"
                />
              </div>
              <el-button
                link
                type="primary"
                :disabled="issueDisabled"
                @click="issueClick"
                >下发</el-button
              >
            </div>
          </div>
        </div>
        <div class="drawer-four">
          <el-divider content-position="left">适配状态</el-divider>
          <div class="four-status-main">
            <div class="four-item">
              <div class="four-title">协议适配状态</div>
              <el-tag class="custom-tag">{{ protocolStatus }}</el-tag>
            </div>
            <div class="four-item">
              <div class="four-title">边缘网关状态</div>
              <el-tag class="custom-tag">{{ gatewayStatus }}</el-tag>
            </div>
          </div>
        </div>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <!-- <el-button @click="cancelClick">取消</el-button> -->
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style>
.el-drawer__body::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  background-color: #f5f5f5;
}

.el-drawer__body::-webkit-scrollbar {
  width: 8px;
  background-color: #f5f5f5;
}

.el-drawer__body::-webkit-scrollbar-thumb {
  border-radius: 8px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  background-color: #8b8b8b;
}
</style>
<style lang="scss" scoped>
.form-btn {
  margin-top: 30px;
}

.form-table {
  padding-bottom: 20px;
}

.config-btn {
  text-align: right;
}
.drawer-main {
  height: 100%;
  display: flex;
  flex-direction: column;

  .drawer-one {
    flex: 0 0 auto;
  }

  .drawer-one1 {
    display: flex;
    justify-content: flex-end;
    align-items: center; /* 垂直方向居中对齐 */
  }

  .drawer-two {
    flex: auto;
    .form-title {
      font-size: 18px;
      font-weight: 700;
      padding-bottom: 18px;
    }
  }

  .drawer-three {
    flex: 0 0 auto;

    .three-main {
      .three-item {
        display: flex;
        align-items: center;

        .progress-box {
          padding-right: 20px;
          flex: 1;
        }
      }

      .three-item + .three-item {
        margin-top: 15px;
      }
    }
  }

  .drawer-four {
    flex: 0 0 auto;

    .four-status-main {
      display: flex;
      justify-content: space-around;

      .four-item {
        .four-title {
          text-align: center;
          font-size: 16px;
          padding-bottom: 5px;
        }

        .custom-tag {
          width: 200px;
          background-color: #f5f7fa;
        }
      }
    }
  }
}
</style>
